package cl.golive.d2menu.dal;

import cl.golive.d2menu.utils.dbUtils.DataBaseConn;
import cl.golive.d2menu.obj.Plato;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author whyem
 */
public class PlatoDAL {

    private DataBaseConn dbConn;
    
    public PlatoDAL() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        this.dbConn = new DataBaseConn();
        this.dbConn.openConnection();
    }

    public List<Plato> traerPlatosPorCategoria(int categoriaId) throws SQLException {
        List<Plato> platosList = new ArrayList();

        String query="SELECT * FROM plato WHERE categoria_id="+categoriaId+";";
        System.out.println("> Query: "+query);

        ResultSet result = this.dbConn.selectSQL(query);
        ResultSetMetaData metaData = result.getMetaData();
        int columns = metaData.getColumnCount();

        ArrayList results = new ArrayList();

        while (result.next()){
            HashMap row = new HashMap();
            results.add(row);
            for(int i=1; i<=columns; i++){
                row.put(metaData.getColumnName(i),result.getObject(i));
            }

        }
        this.dbConn.closeConnection();
        platosList = mappingResultadoToPlato(results);
        return platosList;
    }

    private List<Plato> mappingResultadoToPlato(ArrayList results) {
        List<Plato> platosColl = new ArrayList<Plato>();

        for(int i=0;i<results.size();i++) {
            Plato plato = new Plato();

            HashMap row = (HashMap) results.get(i);
            plato.setPlatoId(Integer.parseInt(row.get("id_plato").toString()));
            plato.setCategoriaId(Integer.parseInt(row.get("categoria_id").toString()));
            plato.setNombrePlato(row.get("nombre_plato").toString());
            plato.setDetallePlato(row.get("detalle_plato").toString());
            plato.setPrecio(Integer.parseInt(row.get("precio").toString()));
            plato.setNombreImagen(row.get("nombre_imagen").toString());

            platosColl.add(plato);
        }
        return platosColl;
    }

}
